//
//  WLPhotoLookVController.m
//  WanLian
//
//  Created by muzhuang on 2018/11/3.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLPhotoLookVController.h"
#import "WLCloudMoreView.h"
#import "WLFileRenameAlertView.h"
#import "WLCloudDetailVController.h"
#import "WLDeleteAlertView.h"
#import "WLCommonTool.h"
#import "HXPhotoTools.h"
#import "WLFileSocketManager.h"
#import "WLFileRequest.h"
#import "WLFileUpDownLoadModel.h"
#import "WLDownLoadCenter.h"
#import "WLDataBaseManager.h"
#import "HXPhotoTools.h"
#import "WLSaveAblumToLocal.h"
#import "WLFileHandle.h"
#import "UIImage+ext.h"

@interface WLPhotoLookVController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIImageView *ivPhoto;
@property (nonatomic, strong) UIScrollView *scrollPhoto;
@property (nonatomic, strong) WLFileUpDownLoadModel *model;
@property (nonatomic, weak) UIView *photoLoadFailView;



@end

@implementation WLPhotoLookVController

- (UIView *)photoLoadFailView {
    if (_photoLoadFailView == nil) {
        _photoLoadFailView = [[[NSBundle mainBundle] loadNibNamed:@"PhotoLoadFail" owner:nil options:nil]firstObject];
        _photoLoadFailView.frame = self.view.bounds;
    }
    return _photoLoadFailView;
}
- (void)viewDidDisappear:(BOOL)animated  {
    [super viewDidDisappear:animated];
    [self.model.dataTask cancel];
    [SVProgressHUD dismiss];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"照片";
    if (self.isLocal == NO) {
        UIButton *btnUpDown = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
        [btnUpDown setImage:[UIImage imageNamed:@"cloud_more"] forState:UIControlStateNormal];
        [btnUpDown addTarget:self action:@selector(moreInfoAction) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithCustomView:btnUpDown];
        self.navigationItem.rightBarButtonItem = rightBar;
    }
    
    _scrollPhoto = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, HEIGHT_SCREEN_WL-WL_NavTopHeight)];//scrollView作为背景
    _scrollPhoto.delegate = self;
    _scrollPhoto.userInteractionEnabled = YES;
    _scrollPhoto.showsHorizontalScrollIndicator = YES;//是否显示侧边的滚动栏
    _scrollPhoto.showsVerticalScrollIndicator = NO;
    _scrollPhoto.scrollsToTop = NO;
    _scrollPhoto.scrollEnabled = YES;
//    _scrollPhoto.backgroundColor = [UIColor blackColor];
    
    UITapGestureRecognizer *tapBg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBgViewGestureR:)];
    [tapBg setNumberOfTapsRequired:2];
    [_scrollPhoto addGestureRecognizer:tapBg];
    
    _ivPhoto = [[UIImageView alloc] initWithFrame:_scrollPhoto.bounds];
//    _ivPhoto.contentMode = UIViewContentModeScaleAspectFill;
    _ivPhoto.contentMode = UIViewContentModeScaleAspectFit;
//    [_ivPhoto sd_setShowActivityIndicatorView:YES];
//    [_ivPhoto sd_setIndicatorStyle:UIActivityIndicatorViewStyleGray];
    if (self.isLocal == YES) {
        [self showImage];
        
    } else {
        //先请求本地数据
        NSArray *resu = [self queryLocal];
        if (resu.count > 0) {
            [self showImage];
        } else {
            [_ivPhoto sd_setImageWithURL:[NSURL URLWithString:_photoModel.url] placeholderImage:nil];
            [self requestPhoto];
        }
    }
    
    [_scrollPhoto addSubview:_ivPhoto];
    [self.view addSubview:_scrollPhoto];
    
//    WLWkSelf
//    [_scrollPhoto mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(weakSelf.view);
//    }];
    
    //最大放大比例
    _scrollPhoto.maximumZoomScale = 2;
//    [_scrollPhoto setZoomScale:0.5f animated:NO];
}
- (NSArray *)queryLocal {
    NSArray *resultArr = [[WLDownLoadCenter shareInstance] queryModelWithFileName:self.photoModel.fileName];
    self.model = resultArr.firstObject;
    return resultArr;
}
- (void)showImage {
    NSString *localIdentifier = nil;
    NSURL *fileURL = nil;
    
    if (self.isLocal == YES) {
        localIdentifier = self.photoModel.localIdentifier;
        fileURL = self.photoModel.fileURL;
    } else {
        localIdentifier = self.model.localIdentifier;
        fileURL = self.model.fileURL;
    }
    
    if (localIdentifier) {
        WLWkSelf
        [HXPhotoTools getHighQualityFormatPhotoWithLocalIdentifier:localIdentifier size:self.ivPhoto.frame.size completion:^(UIImage *image, NSDictionary *info) {
            if (image) {
                weakSelf.ivPhoto.image = image;
            } else {
                [weakSelf configFailState];
            }
        } error:nil];
    } else if (fileURL) {
        if ([WLFileHandle isExistsAtPath:fileURL.path]) {
            UIImage *image = [UIImage imageWithContentsOfFile:fileURL.path];
            if (image) {
                _ivPhoto.image = image;
            } else {
                [self configFailState];
            }
        } else {
            [self configFailState];
        }
    } else {
        [self configFailState];
    }
    
    
}

- (void)configFailState {
    
    [self.view addSubview:self.photoLoadFailView];
}
- (void)requestPhoto {
    [SVProgressHUD showWithStatus:@"图片加载中"];
    WLFileUpDownLoadModel *model = [[WLFileUpDownLoadModel alloc] init];
    model.requestURL = self.photoModel.filePath;
    model.fileType = SPFileTypePhoto;
    model.loadState = FileLoadingStateRunning;
    model.fileName = self.photoModel.fileName;
    model.fileTotalBytes = self.photoModel.fileSize * KB_UNIT;
    model.isUpLoad = NO;
    WLFileSocketManager *socketManager = [WLFileSocketManager shareInstance];
    WLFileRequest *request = [model getRequestModelNotSave];
    request.host = [WLCommonTool getFileUpDownloadHost];
    request.port = 9002;
    WLWkSelf
    WLSocketWorker *dataTask =  [socketManager downloadTaskWithModel:request progress:^(float process, long expected, long loaded) {
        model.process = process;
    }  success:^(NSDictionary * _Nonnull successDict) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf dealWithSuccess:successDict model:model];
        });
    } failure:^(NSString * _Nonnull errorMsg, NSInteger errorTag) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf dealWithFailure:errorMsg errorTag:errorTag model:model];
        });
    } error:^(NSError * _Nonnull error) {
        
    }];
    model.dataTask = dataTask;
    self.model = model;
}

- (void)dealWithSuccess:(NSDictionary *)successDict model:(WLFileUpDownLoadModel *)model {
    
    [SVProgressHUD dismiss];
    model.loadState = FileLoadingStateComplete;
    if (successDict[@"localURL"]) {
        model.fileURL = successDict[@"localURL"];
    }
//    model.mediaLocalURL = successDict[@"localMediaURL"];
    model.comleteTime = [NSString getNowStrWithFormater:@"yyyy/MM/dd HH:mm"];
    [[WLDownLoadCenter shareInstance] saveTaskToDataBaseWithModel:model];
    if (model.fileURL) {
        NSData *data = [NSData dataWithContentsOfFile:self.model.fileURL.path];
        _ivPhoto.image = [UIImage imageWithData:data];
    }
}
- (void)dealWithFailure:(NSString *)errorMsg errorTag:(NSInteger)errorTag  model:(WLFileUpDownLoadModel *)model {
    model.loadState = FileLoadingStateFail;
    [SVProgressHUD dismiss];
    [self configFailState];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _ivPhoto;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat offsetX = (_scrollPhoto.bounds.size.width > _scrollPhoto.contentSize.width)?(_scrollPhoto.bounds.size.width - _scrollPhoto.contentSize.width) *0.5 : 0.0;
    CGFloat offsetY = (_scrollPhoto.bounds.size.height > _scrollPhoto.contentSize.height)?
    (_scrollPhoto.bounds.size.height - _scrollPhoto.contentSize.height) *0.5 : 0.0;
    _ivPhoto.center =CGPointMake(_scrollPhoto.contentSize.width *0.5 + offsetX,_scrollPhoto.contentSize.height *0.5 + offsetY);
}

- (void)tapBgViewGestureR:(UITapGestureRecognizer *)tapGR
{
    CGFloat newScale;
    if(_scrollPhoto.zoomScale>1){
        newScale=1.0;
    }
    else{
        newScale=2;
    }
//    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[sender locationInView:sender.view]];
    CGRect zoomRect;
    zoomRect.size.height =_scrollPhoto.frame.size.height / newScale;
    zoomRect.size.width  =_scrollPhoto.frame.size.width  / newScale;
    zoomRect.origin.x = _ivPhoto.center.x - (zoomRect.size.width  /2);
    zoomRect.origin.y = _ivPhoto.center.y - (zoomRect.size.height /2);
    
    [_scrollPhoto zoomToRect:zoomRect animated:YES];
}

- (void)moreInfoAction
{
    if (self.model.loadState == FileLoadingStateRunning||self.model.loadState == FileLoadingStateWaiting) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"图片正在加载中，请稍后再试" delayTime:2.f];
        return;
    }
    WLWkSelf
    [WLCloudMoreView showMoreViewTitle:@"照片" action:^(NSInteger index) {
        if (index==0) {
            [weakSelf photoDownload];
        }
        else if (index==1)
        {
            [self deletePhotoAction];
        }
        else if (index==2)
        {
            [self renameAction];
        }
        else if (index==3)
        {
            WLCloudDetailVController *detailController = [[WLCloudDetailVController alloc] init];
            WLCloudFileModel *fileMOdel = [[WLCloudFileModel alloc] init];
            fileMOdel.fileName = weakSelf.photoModel.fileName;
            fileMOdel.filePath = weakSelf.photoModel.filePath;
            fileMOdel.uploadTime = weakSelf.photoModel.uploadTime;
//            NSData *imageData = UIImagePNGRepresentation(weakSelf.ivPhoto.image);
            long fileSize = weakSelf.photoModel.fileSize;
            fileMOdel.fileSize = [NSString stringWithFormat:@"%ld",fileSize];
            detailController.fileModel = fileMOdel;
            [weakSelf.navigationController pushViewController:detailController animated:YES];
        }
    }];
}

- (void)photoDownload
{
    if (self.model.loadState != FileLoadingStateComplete) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"图片正在下载中，请稍后再试" delayTime:2.f];
        return;
    }
    if (self.model.mediaLocalURL) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"已保存到手机相册" delayTime:2.f];
        return;
    }
    WLSaveAblumToLocal *library = [[WLSaveAblumToLocal alloc] init];
    WLWkSelf
    [library writeImageDataToSavedPhotosAlbumWithURL:self.model.fileURL metadata:[NSDictionary dictionary] completionBlock:^(NSURL * _Nonnull assetURL, NSError * _Nonnull error, NSString * _Nonnull localIdentifier) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (assetURL) {
                [SVProgressHUD showAndAutoCloseWithStatus:@"已保存到手机相册" delayTime:2.f];
                weakSelf.model.mediaLocalURL = assetURL;
                weakSelf.model.localIdentifier = localIdentifier;
                [WLFileHandle removeItemAtPath:weakSelf.model.fileURL.path error:nil];
                weakSelf.model.fileURL = [NSURL fileURLWithPath:@""];
                weakSelf.model.showInCompleteList = YES;
                [[WLDownLoadCenter shareInstance] updateTaskToDataBaseWithModel:weakSelf.model];
            }
        });
    }];
//    UIImageWriteToSavedPhotosAlbum(_ivPhoto.image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);

}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        [self showHUDMessage:@"已下载到手机相册"];
    }
//    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

- (void)deletePhotoAction
{
    WLWkSelf
    WLDeleteAlertView *bindingView = [[WLDeleteAlertView alloc] initWithTitle:_photoModel.fileName];
    bindingView.okAction = ^{
        [weakSelf deletePhoto];
    };
    [bindingView show];
}

- (void)deletePhoto
{
    WLWkSelf
    
    NSString *url = nil;
    if ([WLCommonTool isConnectedTianYiLian]) {
        url = [NSString stringWithFormat:@"%@/cgi-bin/luci/file/upload/deleteitem?filePath=%@", HTTP_HOST_ROUTER, self.photoModel.srcFilePath];
    } else {//https://www.zeerong.com/router/web/storage/item/delete?key=c12478fa924e3371283f2b9a0bfc921a&filepath=/mnt/mmcblk0p1/photo/1.jpg
        url = [NSString stringWithFormat:@"%@/storage/item/delete?key=%@&filepath=%@", HTTP_HOST_WEB,[[WLUseManager shareUser] getUserCurrentRouter], self.photoModel.srcFilePath];
    }
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:url withParamsDic:nil success:^(NSDictionary *successDict) {
        [weakSelf showHUDMessage:successDict[@"message"]];
        [self.navigationController popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:KRRefreshPhotoCloudNotification object:nil];
        [[WLDownLoadCenter shareInstance] deleteDataBaseWithModel:weakSelf.model];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)renameAction
{
    WLWkSelf
    WLFileRenameAlertView *bindingView = [[WLFileRenameAlertView alloc] initWithTitle:@"重命名文件"];
    bindingView.okAction = ^(NSString * _Nonnull strAddr) {
        [weakSelf renameFile:strAddr];
    };
    [bindingView setOriginContent:[self.photoModel.fileName filterExtension]];
    [bindingView show];
}

- (void)renameFile:(NSString *)strName
{
    NSString *originNameSuffix = self.photoModel.fileName.pathExtension;
    strName = [NSString stringWithFormat:@"%@.%@", strName, originNameSuffix];
    WLWkSelf
    
    NSString *url = nil;
    if ([WLCommonTool isConnectedTianYiLian]) {
        url = [NSString stringWithFormat:@"%@/cgi-bin/luci/file/upload/renameitem?srcFilePath=%@&dstFilePath=%@%@", HTTP_HOST_ROUTER, self.photoModel.srcFilePath, self.photoModel.relatePath, strName];
    } else {//https://www.zeerong.com/router/web/storage/item/delete?key=c12478fa924e3371283f2b9a0bfc921a&src=/mnt/mmcblk0p1/photo/1.jpg&dst=/mnt/mmcblk0p1/photo/2.jpg
        url = [NSString stringWithFormat:@"%@/storage/item/rename?key=%@&src=%@&dst=%@%@", HTTP_HOST_WEB, [[WLUseManager shareUser] getUserCurrentRouter], self.photoModel.srcFilePath, self.photoModel.relatePath, strName];
    }
//    NSString *urlStr = [NSString stringWithFormat:@"/cgi-bin/luci/file/upload/renameitem?srcFilePath=%@&dstFilePath=%@%@", self.photoModel.srcFilePath, self.photoModel.relatePath, strName];
//    urlStr = [WLCommonTool getRealURLWithUrlStr:urlStr];
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:url withParamsDic:nil success:^(NSDictionary *successDict) {
        NSString *newFilePath = [weakSelf.photoModel.filePath stringByReplacingOccurrencesOfString:weakSelf.photoModel.fileName withString:strName];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        if (weakSelf.photoModel.fileName.length > 0) {
            [dict setObject:weakSelf.photoModel.fileName forKey:@"fileName"];
        }
        weakSelf.photoModel.filePath = newFilePath;
        weakSelf.photoModel.fileName = strName;
        weakSelf.model.fileName = strName;
        weakSelf.model.requestURL = newFilePath;
        [[WLDownLoadCenter shareInstance] updateTaskToDataBaseWithModel:weakSelf.model condictionDict:dict];
        
        [weakSelf showHUDMessage:@"修改成功"];
        [[NSNotificationCenter defaultCenter] postNotificationName:KRRefreshPhotoCloudNotification object:nil];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {

    } inView:self.view];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
